function template(str, data) {
    var o = data;
    return str.replace(/\{\{(.*?)\}\}/g, function (match, token) {
        return eval("o." + token);
    });
}

grd_transaksi={}
grd_transaksi.QueryForm =
	// QUERY FORM
	function (){

		// DETECT TRANSAKSI FORM
		var frmTransaksi = $('form.frm-transaksi');

		if( frmTransaksi.length > 0){
			//console.log('Hello')
			// DONT DO TWICE
			grd_transaksi.QueryForm.Reset=false;
			//transaksi = true;
			// $('.flexigrid.grd-transaksi a.edit_button, .flexigrid.grd-transaksi a.add_button').each(function(i,button){
			// 	if(!$(button).data('hasClickHandler')){
			// 		$(button).click(function(){
			// 			QFORM.transaksi=false;
			// 			QueryForm();
			// 		})	
			// 		$(button).data('hasClickHandler',true);
			// 		//console.log(button);
			// 	}
			// });
			// UPDATE FORM TRASAKSI VIEW
			//
			//console.log(parent.base_url);
			$.get(parent.base_url()+'assets/templates/form/_transaksi.php',function(r){
				var fields = ["cert_no", "ref_invoice_no", "ref_invoice_date", "ref_packing_no", "ref_packing_date", "ref_awb_no", "ref_awb_date", "inspected_goods", "coi_date", "coi_ttd", "roi_no", "roi_date", "roi_ref1", "roi_ref2", "roi_ref3", "roi_result1", "roi_result2", "roi_result3", "roi_inspector", "io_no", "ql_no"];
				var data = {};
				
				//console.log(data)
				//var frm = template(r,data);

				frmTransaksi.find('.form-div').append(r);
				$.each(fields,function(i,field){
					var el = frmTransaksi.find('div#'+field+'_field_box');
					var input = el.find('#field-'+field);
					frmTransaksi.find('.form-div #tpl_'+field).replaceWith(input);
					el.hide();
					//console.log(input)
				});

				frmTransaksi.find('#field-Importir').autocomplete({
					source: function(request, response){
					 $.ajax({ 
					    url: parent.base_url()+'master/importir_ac',
					    data: { 
					       term: $('#field-Importir').val()
					    },
					    dataType: "json",
					    type: "POST",
					    success: function(data){
					       response(data);
					    }
					 });
					},
					// 
					select: function(event, ui) { 
						var imp = ui.item.data; 
						$('#field-NPWP').val(imp.npwp);
						$('#field-Nomor_API').val(imp.no_api);
						$('#field-Tanggal_API').val(imp.tgl_api);
						$('#field-Alamat_Importir').val(imp.alamat);
						$('#field-Telp_Importir').val(imp.telepon);
						$('#field-Fax_Importir').val(imp.fax);
                	}
					// 
				});
			});
		}

		//console.log(grd_transaksi.QueryForm.Reset)
		if(grd_transaksi.QueryForm.Reset){
			setTimeout(function(){
				grd_transaksi.QueryForm();
			},300);
		}
	}
grd_transaksi.QueryForm.Reset = true;
grd_detail_transaksi={}
grd_detail_transaksi.QueryForm =
	// QUERY FORM
	function (){

		// DETECT TRANSAKSI FORM
		var frmDetailTransaksi = $('form.frm-detail-transaksi');

		if( frmDetailTransaksi.length > 0){
			//console.log('Hello')
			// DONT DO TWICE
			grd_detail_transaksi.QueryForm.Reset=false;
			
			// EXECUTE code
			console.log('DO CHANGE ON YOUR FORM');

			// 
			$('#seq_no_display_as_box').text('Seq No :');
			$('#HS_display_as_box').text('HS :');

			// BUILD CALCULATOR
			var lbl = $('<label></label>');
			var inp = $('<input type="text"/>');
			var b  = $('<b></b>').addClass('btitle');
			var dv = $('<div></div>').addClass('usd-calc');
			var dv1 = $('<div></div>').addClass('usd-calc-header').append(b.clone(true).text('Kalkulator USD'));
			
			var cb  = function(){
				var _in = parseFloat($('.usd-calc-in input.in').val());
				var _conf= parseFloat($('.usd-calc-conf input.inconf').val());

				$('.usd-calc-out input.out').val(_in*_conf);

			};
			var cb_cmd  = function(){
				$('.form-div input[name=nilai_usd]').val($('.usd-calc-out input.out').val());
			};
			var dv2 = $('<div></div>').addClass('usd-calc-conf')
					  dv2.append(lbl.clone(true).text('Kurs USD'));
					  dv2.append(inp.clone().addClass('inconf').keyup(cb))		
			var dv3 = $('<div></div>').addClass('usd-calc-in');
					  dv3.append(lbl.clone(true).text('Nilai USD'));
					  dv3.append(inp.clone().addClass('in').val($('.form-div input[name=nilai_usd]').val()).keyup(cb))
			var dv4 = $('<div></div>').addClass('usd-calc-out');
					  dv4.append(lbl.clone(true).text('Kurs Rupiah'));
					  dv4.append(inp.clone().addClass('out'));
			var dv5 = $('<div></div>').addClass('usd-calc-cmd');
			
					  dv4.append($('<input type="button" value="Set">').css('margin','2px').click(cb_cmd));
					  
			dv.append(dv);
			dv.append(dv1);
			dv.append(dv2);
			dv.append(dv3);
			dv.append(dv4);
			dv.append(dv5);
			dv.css({position:'absolute','border':'solid 1px #000'});
			dv.draggable();

			//dv.find('input')
			frmDetailTransaksi.find('.form-div').append(dv);

		}

		//console.log(grd_transaksi.QueryForm.Reset)
		if(grd_detail_transaksi.QueryForm.Reset){
			setTimeout(function(){
				grd_detail_transaksi.QueryForm();
			},300);
		}
	}
grd_transaksi.QueryForm.Reset = true;

$(document).ready(function() {

	$("body").on({
    	click:function(){
       		$.getJSON($(this).prop('href'),function(o){
				//console.log(o);

				if(typeof o.status != 'undefined')
				{
					alert('Transaksi ' + o.status.replace(/_/g,' '));
					if(o.status == 'sudah_dikirim')
					{
						$('.grd-transaksi #ajax_refresh_and_loading').click();
					}
				}
			});
			return false;
    	},
    	mouseover:function(){	$(this).prop('title','Ubah Status Kirim');}
	}, '.grd-transaksi a.transaksi_kirim_cmd');
	$("body").on({mouseover:function(){	$(this).prop('title','Detail Transaksi');}},'.grd-transaksi a.transaksi_detail_cmd');

	$("body").on({
		click:function(){

			var url = $(this).prop('href');
   			var dlg = $('<div id="upwdlg"></div>');
   			var cnt = '<div class="pengguna-password">'+
				'<div>'+
					'<label style="display: block; width: 87px; float: left; line-height: 22px;">Password :</label>'+
					'<input style="float:left;margin-top:1px;" type="password" name="pengguna_password"/>' +
				'</div><div><input  style="float:left;cursor:pointer;margin-left:2px" type="button" value="Set" class="cmd_set_passwd"/></div>' +
			'</div>';
			var dlg_title = 'Ubah Password - ' + $.trim($(this).parent().parent().next().text());
			dlg.html(cnt).dialog({
				modal:true,
				title:dlg_title,
				width:328,
				height:80,
				close:function(){
					dlg.remove();
				}
			});
			
			dlg.find('input.cmd_set_passwd').click(function(){
				var new_passwd = dlg.find('input[name=pengguna_password]').val();
				if(!new_passwd.length){
					alert('Mohon lengkapi data Anda !')
					return;
				}

				
				$.post(url,{passwd:new_passwd},function(o){
					alert(o);
					dlg.dialog('close')	;
				});	
			})
			dlg.find('input[name=pengguna_password]').keydown(function(e){
				if(e.keyCode==13){
					dlg.find('input.cmd_set_passwd').click();
				}
			});
			dlg.dialog('open');
   			
			return false;
    	},
		mouseover:function(){	$(this).prop('title','Ubah Password');}
	},'.grd-pengguna a.pengguna_password_cmd');
//////////////////////
grd_quotation_letter={}
grd_quotation_letter.QueryForm =
	// QUERY FORM
	function (){

		// DETECT TRANSAKSI FORM
		var frmQL = $('form.frm-quotation-letter');

		if( frmQL.length > 0){
			// DONT DO TWICE
			grd_quotation_letter.QueryForm.Reset=false;
			
			frmQL.find('#ql_price_display_as_box').text('');
			frmQL.find('#ql_charge_display_as_box').text('');
			var t = frmQL.find('#ql_charge_input_box');
			frmQL.find('#ql_charge_curr_input_box').after(t);
			var u = frmQL.find('#ql_price_input_box');
			frmQL.find('#ql_price_curr_input_box').after(u);
			frmQL.find('#ql_charge_field_box,#ql_price_field_box').hide();
			//frmQL.find('#field_ql_price_curr_chzn .chzn-single.chzn-default span').text('--CURR--');
		}

		/////
		frmQL.find('#field-Importir').autocomplete({
			source: function(request, response){
			 $.ajax({ 
			    url: parent.base_url()+'master/importir_ac',
			    data: { 
			       term: $('#field-Importir').val()
			    },
			    dataType: "json",
			    type: "POST",
			    success: function(data){
			       response(data);
			    }
			 });
			},
			// 
			select: function(event, ui) { 
				var imp = ui.item.data; 
				//$('#field-ql_attn').val(imp.npwp);
				$('#field-Nomor_API').val(imp.no_api);
				$('#field-Tanggal_API').val(imp.tgl_api);
				$('#field-Alamat_Importir').val(imp.alamat);
				$('#field-Telp_Importir').val(imp.telepon);
				$('#field-Fax_Importir').val(imp.fax);
        	}
			// 
		});
		//console.log(grd_quotation_letter.QueryForm.Reset)
		if(grd_quotation_letter.QueryForm.Reset){
			setTimeout(function(){
				grd_quotation_letter.QueryForm();
			},300);
		}
	}
grd_quotation_letter.QueryForm.Reset = true;


grd_inspection_order={}
grd_inspection_order.QueryForm =
	// QUERY FORM
	function (){

		// DETECT TRANSAKSI FORM
		var frmIO = $('form.frm-inspection-order');

		if( frmIO.length > 0){
			// DONT DO TWICE
			grd_inspection_order.QueryForm.Reset = false;

			var dvLbl = $('<div></div>').css({'background':'#cecece','padding':'2px','font-weight':'bold'});
			frmIO.find('#io_from_name_field_box').before(dvLbl.clone().text('Dari : '));
			frmIO.find('#io_to_field_box').before(dvLbl.clone().text('Kepada : '));
			frmIO.find('#Importir_field_box').before(dvLbl.clone().html('&nbsp;'));
			
			/* SCOPE OF WORK */
			var scopeOfWork = $('<div></div>').addClass('form-field-box scope-of-work');
			var ID = frmIO.prop('action').split('/').pop();
			frmIO.find('#io_contact_name_field_box').before(scopeOfWork);
			//console.log(ID);
			$.get(base_url()+'inspection/scope_ceklist/'+ID,function(r){
				frmIO.find('div.scope-of-work').html(r);
			});
			
			//
			frmIO.find('#io_contact_name_field_box').before(dvLbl.clone().text('Informasi Kontak Pemeriksaan :'));

			var frmAction = frmIO.attr('action');

			if( frmAction.match(/insert$/))
			{
				$.getJSON(base_url()+'inspection/from_config',function(j){
					//console.log(j)
					// SET DEFAULT
					$('#field-io_from_name').val(j.kop_from);
					$('#field-io_from_tel').val(j.kop_tel);
					$('#field-io_from_fax').val(j.kop_fax);
					$('#field-io_from_email').val(j.kop_email);
					$('#field-io_from_attn').val(j.rekening_nama);
					// 
				})
			}

			frmIO.find('#field-Importir').autocomplete({
				source: function(request, response){
				 $.ajax({ 
				    url: parent.base_url()+'master/importir_ac',
				    data: { 
				       term: $('#field-Importir').val()
				    },
				    dataType: "json",
				    type: "POST",
				    success: function(data){
				       response(data);
				    }
				 });
				},
				// 
				select: function(event, ui) { 
					var imp = ui.item.data; 
					//$('#field-ql_attn').val(imp.npwp);
					//$('#field-Nomor_API').val(imp.no_api);
					//$('#field-Tanggal_API').val(imp.tgl_api);
					$('#field-Alamat_Importir').val(imp.alamat);
					$('#field-Telp_Importir').val(imp.telepon);
					$('#field-Fax_Importir').val(imp.fax);
	        	}
				// 
			});
		}
		

		//console.log(grd_inspection_order.QueryForm.Reset)
		if(grd_inspection_order.QueryForm.Reset){
			setTimeout(function(){
				grd_inspection_order.QueryForm();
			},300);
		}
	}
grd_inspection_order.QueryForm.Reset = true;	
/////////////


$("body").on({
	click:function(){	
		
		//console.log(state);
		var serial = {};
		var nl = $('.frm-inspection-order .form-input-box .scope .set');
		var cx = nl.length;
		while( cx >= 0 ){
			var n = nl.get(cx);
			var id = $(n).attr('rowid');
			if(id){
				//console.log(id)
				var state = $(n).prop('checked') ? '1': '0';
				serial[id]=state;
			}
			cx--;
		}

		//console.log();
		$('input[name=ql_scope_of_work]').val(JSON.stringify(serial));
	}}
	,'.frm-inspection-order .form-input-box .scope input.set');

/////
// GRD RFI

grd_request_for_inspection={}
grd_request_for_inspection.QueryForm =
	// QUERY FORM
	function (){

		// DETECT TRANSAKSI FORM
		var frmRFI = $('form.frm-request-for-inspection');

		if( frmRFI.length > 0){
			//console.log('Hello')
			// DONT DO TWICE
			grd_request_for_inspection.QueryForm.Reset=false;
			//transaksi = true;
			// $('.flexigrid.grd-transaksi a.edit_button, .flexigrid.grd-transaksi a.add_button').each(function(i,button){
			// 	if(!$(button).data('hasClickHandler')){
			// 		$(button).click(function(){
			// 			QFORM.transaksi=false;
			// 			QueryForm();
			// 		})	
			// 		$(button).data('hasClickHandler',true);
			// 		//console.log(button);
			// 	}
			// });
			// UPDATE FORM TRASAKSI VIEW
			//
			//console.log(parent.base_url);
			$.get(parent.base_url()+'assets/templates/form/_request_for_inspection.php',function(r){
				//TO GET THIS VALUE QUICKLY RUN AT FIREBUGS
				// nl=document.getElementsByTagName('input');a=[];for(i in nl){a.push(nl[i].name)};a;
				// nl=document.getElementsByTagName('select');a=[];for(i in nl){a.push(nl[i].name)};a;

				var fields = ["no_srt","tgl_srt","id_afiliasi","to","to_attn","to_address","to_telp","to_fax","to_email","from","from_attn","from_address","from_telp","from_fax","from_email","subject","name","subject_oi","description_og","importer","importer_attn","importer_address","importer_telp","importer_fax","importer_email","exporter","exporter_attn","exporter_address","exporter_telp","exporter_fax","exporter_email","place_oi","date_oi","import_permit_no","invoice_no","quotation_no","quotation_date","company_name","company_npwp","company_address","regard","applicants_name"];
				var data = {};
				
				//console.log(data)
				//var frm = template(r,data);

				frmRFI.find('.form-div').append(r);
				$.each(fields,function(i,field){
					var el = frmRFI.find('div#'+field+'_field_box');
					var input = el.find('#field-'+field);
					frmRFI.find('.form-div #tpl_'+field).replaceWith(input);
					el.hide();
					//console.log(input)
				});

				/////



				//////
			});
			frmRFI.find('#field-importer').autocomplete({
				source: function(request, response){
				 $.ajax({ 
				    url: parent.base_url()+'master/importir_ac',
				    data: { 
				       term: $('#field-importer').val()
				    },
				    dataType: "json",
				    type: "POST",
				    success: function(data){
				       response(data);
				    }
				 });
				},
				// 
				select: function(event, ui) { 
					var imp = ui.item.data; 
					//$('#field-ql_attn').val(imp.npwp);
					//$('#field-Nomor_API').val(imp.no_api);
					//$('#field-importer_email').val(imp.tgl_api);
					$('#field-importer_address').val(imp.alamat);
					$('#field-importer_telp').val(imp.telepon);
					$('#field-importer_fax').val(imp.fax);
	        	}
				// 
			});
		}

		//console.log(grd_request_for_inspection.QueryForm.Reset)
		if(grd_request_for_inspection.QueryForm.Reset){
			setTimeout(function(){
				grd_request_for_inspection.QueryForm();
			},300);
		}
	}
grd_request_for_inspection.QueryForm.Reset = true;

grd_quotation={}
grd_quotation.QueryForm =
	// QUERY FORM
	function (){

		// DETECT TRANSAKSI FORM
		var frmQ = $('form.frm-quotation');

		if( frmQ.length > 0){
			//console.log('Hello')
			// DONT DO TWICE
			grd_quotation.QueryForm.Reset=false;
			//transaksi = true;
			// $('.flexigrid.grd-transaksi a.edit_button, .flexigrid.grd-transaksi a.add_button').each(function(i,button){
			// 	if(!$(button).data('hasClickHandler')){
			// 		$(button).click(function(){
			// 			QFORM.transaksi=false;
			// 			QueryForm();
			// 		})	
			// 		$(button).data('hasClickHandler',true);
			// 		//console.log(button);
			// 	}
			// });
			// UPDATE FORM TRASAKSI VIEW
			//
			//console.log(parent.base_url);

			$.get(parent.base_url()+'assets/templates/form/_quotation.php',function(r){
				//TO GET THIS VALUE QUICKLY RUN AT FIREBUGS
				// nl=document.getElementsByTagName('input');a=[];for(i in nl){a.push(nl[i].name)};a;
				// nl=document.getElementsByTagName('select');a=[];for(i in nl){a.push(nl[i].name)};a;

				var fields = ["no_surat", "tgl_surat",'id_afiliasi', "Importir", "Alamat_Importir",
 		"Fax_Importir", "ql_attn", "ql_dear", "ql_subject", "ql_no", "ql_date",
 		"Tanggal_Periksa", "Alamat_Pemeriksaan","ql_price_curr", "ql_price", "ql_vat", "ql_total", "ql_charge_curr", "ql_charge", "idr_bank", 
 		"idr_bank_addr", "idr_bank_ac", "usd_bank", "usd_bank_addr", "usd_bank_ac", "from_name", "from_fax", 
 		"from_email", "ql_tertanda", "ql_jabatan", "ql_jab_init1", "ql_jab_init2"];
 		var data = {};
				
				//console.log(data)
				//var frm = template(r,data);

				frmQ.find('.form-div').append(r);
				$.each(fields,function(i,field){
					var el = frmQ.find('div#'+field+'_field_box');
					var input = el.find('#field-'+field);
					frmQ.find('.form-div #tpl_'+field).replaceWith(input);
					el.hide();
					//console.log(input)
				});

				var ID = frmQ.prop('action').split('/').pop();
				///
				$.getJSON(base_url()+'quotation/form_ceklist/'+ID,function(o){
					frmQ.find('#qlScopeOfWork').html(o.scope);
					frmQ.find('#qlSupportedDoc').html(o.supported_doc);
				});
			
			});
		}

		//console.log(grd_quotation.QueryForm.Reset)
		if(grd_quotation.QueryForm.Reset){
			setTimeout(function(){
				grd_quotation.QueryForm();
			},300);
		}
	}
grd_quotation.QueryForm.Reset = true;

$("body").on({
	click:function(){	
		
		//console.log(state);
		var serial = {};
		var nl = $('.frm-quotation .form-input-box .scope .set');
		var cx = nl.length;
		while( cx >= 0 ){
			var n = nl.get(cx);
			var id = $(n).attr('rowid');
			if(id){
				//console.log(id)
				var state = $(n).prop('checked') ? '1': '0';
				serial[id]=state;
			}
			cx--;
		}

		//console.log();
		$('input[name=ql_scope_of_work]').val(JSON.stringify(serial));
	}}
	,'.frm-quotation .form-input-box .scope input.set');

$("body").on({
	click:function(){	
		
		//console.log(state);
		var serial = {};
		var nl = $('.frm-quotation .form-input-box .supported_doc .set');
		var cx = nl.length;
		while( cx >= 0 ){
			var n = nl.get(cx);
			var id = $(n).attr('rowid');
			if(id){
				//console.log(id)
				var state = $(n).prop('checked') ? '1': '0';
				serial[id]=state;
			}
			cx--;
		}

		//console.log();
		$('input[name=ql_supported_doc]').val(JSON.stringify(serial));
	}}
	,'.frm-quotation .form-input-box .supported_doc input.set');

/**********************/
grd_request_for_quotation={}
grd_request_for_quotation.QueryForm =
	// QUERY FORM
	function (){

		// DETECT TRANSAKSI FORM
		var frmRFQ = $('form.frm-request-for-quotation');

		if( frmRFQ.length > 0){

			grd_request_for_quotation.QueryForm.Reset=false;
			$.get(parent.base_url()+'assets/templates/form/_request_for_quotation.php',function(r){
				//TO GET THIS VALUE QUICKLY RUN AT FIREBUGS
				// nl=document.getElementsByTagName('input');a=[];for(i in nl){a.push(nl[i].name)};a;
				// nl=document.getElementsByTagName('select');a=[];for(i in nl){a.push(nl[i].name)};a;

				var fields = ["roq_no",'id_afiliasi', "roq_date", "roq_to", "to_attn", "to_address",  
				"to_phone", "to_fax", "to_email", "roq_from", "from_attn", "from_address", 
				 "from_phone", "from_fax", "from_email", "subject", "dear_name", 
				"subject_oi","description_og",  "imp_name", "imp_attn", 
				"imp_address", "imp_tel", "imp_fax", "imp_email", 
				"exp_name", "exp_attn", "exp_address", "exp_tel", 
				"exp_fax", "exp_email", "place_oi", "date_oi", 
				"ref_ibl_no", "ref_ip_no", "ref_id_no", "ref_npwp", "ref_inv_no", 
				"ref_dl_year", "ref_tbl_no", "ref_crl", "ref_cin", "reg_name", 
				"reg_applicant"];
 				
 				var data = {};
				
				//console.log(data)
				//var frm = template(r,data);

				frmRFQ.find('.form-div').append(r);
				$.each(fields,function(i,field){
					var el = frmRFQ.find('div#'+field+'_field_box');
					var input = el.find('#field-'+field);
					frmRFQ.find('.form-div #tpl_'+field).replaceWith(input);
					el.hide();
					//console.log(input)
				});

				// var ID = frmRFQ.prop('action').split('/').pop();
				// ///
				// $.getJSON(base_url()+'quotation/form_ceklist/'+ID,function(o){
				// 	frmRFQ.find('#qlScopeOfWork').html(o.scope);
				// 	frmRFQ.find('#qlSupportedDoc').html(o.supported_doc);
				// });
				frmRFQ.find('#field-imp_name').autocomplete({
					source: function(request, response){
					 $.ajax({ 
					    url: parent.base_url()+'master/importir_ac',
					    data: { 
					       term: $('#field-imp_name').val()
					    },
					    dataType: "json",
					    type: "POST",
					    success: function(data){
					       response(data);
					    }
					 });
					},
					// 
					select: function(event, ui) { 
						var imp = ui.item.data; 
						//$('#field-ql_attn').val(imp.npwp);
						//$('#field-Nomor_API').val(imp.no_api);
						//$('#field-Tanggal_API').val(imp.tgl_api);
						$('#field-imp_address').val(imp.alamat);
						$('#field-imp_tel').val(imp.telepon);
						$('#field-imp_fax').val(imp.fax);
		        	}
					// 
				});
			
			
			});
		}

		//console.log(grd_request_for_quotation.QueryForm.Reset)
		if(grd_request_for_quotation.QueryForm.Reset){
			setTimeout(function(){
				grd_request_for_quotation.QueryForm();
			},300);
		}
	}
grd_request_for_quotation.QueryForm.Reset = true;


});